package com.ls.server.service.model.factory.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ls.server.domain.ChatModel;
import com.ls.server.domain.MCPEntity;
import com.ls.server.domain.McpService;
import com.ls.server.service.McpServiceService;
import com.ls.server.service.model.ChatModelClient;
import com.ls.server.service.model.factory.ChatModelFactory;
import com.ls.server.service.model.impl.OpenAIChatModelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * OpenAI 模型工厂实现
 */
@Component
public class OpenAIModelFactory implements ChatModelFactory {

    @Autowired
    private McpServiceService mcpServiceService;

    /**
     * 创建 OpenAI 聊天模型客户端
     *
     * @param model 模型信息
     * @return OpenAI 聊天模型客户端
     */
    @Override
    public ChatModelClient createModel(ChatModel model) {
        ChatModelClient client = new OpenAIChatModelClient();
        var mcpServices = mcpServiceService.getServiceById(model.getMcpServices());
        // 将mcpServices转换为MCPEntity列表
        JSONArray jsonArray = new JSONArray();
        for (McpService tool : mcpServices) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("server", tool.getName());
            jsonObject.put("url", tool.getUrl());
            jsonArray.add(jsonObject);
        }
        // 根据工具封装对象
        MCPEntity mcpEntities = new MCPEntity();
        mcpEntities.setSync(true);
        mcpEntities.setContent(jsonArray.toJSONString());
        client.init(model.getApiKey(), model.getApiUrl(),  model.getCode(), mcpEntities);
        return client;
    }
}
